package com.itany.book.service.impl;

import com.github.pagehelper.PageInfo;
import com.itany.book.service.BookService;
import com.itany.constant.StatusConstant;
import com.itany.exception.FileUploadErrorException;
import com.itany.exception.FlagDisEnableException;
import com.itany.exception.FlageEnableException;
import com.itany.exception.RequestParamException;
import com.itany.mapper.BookMapper;
import com.itany.mapper.ExamineMapper;
import com.itany.pojo.Book;
import com.itany.pojo.Examine;
import com.itany.pojo.Press;
import com.itany.pojo.Supplier;
import com.itany.utils.ParamUtils;
import com.itany.vo.ExamineVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Auther:ws@itany.com
 * Date:20-10-17 上午11:28
 * Version:1.0
 * Description:
 */
@Service
@Transactional
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private ExamineMapper examineMapper;

    @Override
    public PageInfo<Book> findByParam(Integer page, Integer rows, String bookName, String ISBN, Integer pressId, Integer supplierId) {
        List<Book> books = bookMapper.selectBookAll(bookName, ISBN,pressId,supplierId);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return pageInfo;
    }

    @Override
    public List<Supplier> findSupplier() {
        List<Supplier> suppliers = bookMapper.selectSupplier();
        return suppliers;

    }

    @Override
    public List<Press> findPress() {
        List<Press> presses = bookMapper.selectPress();
        return presses;
    }

    @Override
    public void DisEnableFlag(String isbn) throws RequestParamException, FlagDisEnableException {
        if(ParamUtils.isNull(isbn)){
            throw new RequestParamException("请求参数异常");
        }
        Book book=bookMapper.selectByISBN(isbn);
        if(book.getFlag()== 2){
            throw new FlagDisEnableException("状态已禁用");
        }
        if(book.getFlag()== 1){
            book.setFlag(2);
        }
        bookMapper.updateFlag(book);
    }

    @Override
    public void EnableFlag(String isbn) throws RequestParamException, FlageEnableException {
        if(ParamUtils.isNull(isbn)){
            throw new RequestParamException("请求参数异常");
        }
        Book book=bookMapper.selectByISBN(isbn);
        if(book.getFlag()== 1){
            throw new FlageEnableException("状态已启用");
        }
        if(book.getFlag()== 2){
            book.setFlag(1);
        }
        bookMapper.updateFlag(book);
    }

    @Override
    public PageInfo<Examine> examineSupplier(Integer page, Integer rows, String bookname, String isbn, Integer supplierid) {
        ExamineVo vo=new ExamineVo();

        vo.setBookname(bookname);
        vo.setIsbn(isbn);
        vo.setSupplierid(supplierid);

        List<Examine> list = bookMapper.findExamineSupplierAll(vo);
        System.out.println(list.size());
        PageInfo<Examine> info = new PageInfo<Examine>(list);
        return info;
    }

    @Override
    public void addBook(String bookname, String ISBN, String price, String number, String groupprice, String layout, String register, String weight, String bookintroduce, String authorintroduce, String author, String publishdate, String fromat, String pagenumber, String press, MultipartFile file, Integer supplierId) throws RequestParamException, FileUploadErrorException {
        if(ParamUtils.isNull(bookname)){
            throw new RequestParamException("书籍名称不能为空");
        }
        if(ParamUtils.isNull(ISBN)){
            throw new RequestParamException("ISBN不能为空");
        }

        if(ParamUtils.isNull(register)){
            throw new RequestParamException("册数不能为空");
        }

        if(ParamUtils.isNull(weight)){
            throw new RequestParamException("重量不能为空");
        }

        if(ParamUtils.isNull(price)){
            throw new RequestParamException("单价不能为空");
        }
        if(ParamUtils.isNull(number)){
            throw new RequestParamException("数量不能为空");
        }
        if(ParamUtils.isNull(groupprice)){
            throw new RequestParamException("团购价不能为空");
        }
        if(ParamUtils.isNull(layout)){
            throw new RequestParamException("版次不能为空");
        }

        Book book = new Book();
        book.setBookname(bookname);
        book.setIsbn(ISBN);
        book.setBookintroduce(bookintroduce);
        book.setAuthorintroduce(authorintroduce);
        book.setCreatetime(new Date());
//        验证数字格式
        try {
            Double pri = Double.parseDouble(price);
            Double gp = Double.parseDouble(groupprice);
            Integer num = Integer.parseInt(number);
            Integer lo = Integer.parseInt(layout);

            book.setPrice(pri);
            book.setGroupprice(gp);
            book.setNumber(num);
            book.setLayout(lo);
        } catch (NumberFormatException e) {
            throw new RequestParamException("数量，单价等格式错误");
        }

//        查询书籍是否已存在
        Book book1 = bookMapper.selectByISBN(ISBN);
        if (null == book1){
            book.setFlag(StatusConstant.BOOK_DEFAULT_ENFLAG);

            if (null == file){
                bookMapper.insertBook(book);
            }else {
//                生成图片根路径
                String path = StatusConstant.BOOK_IMAGE_ROOT_PATH + new SimpleDateFormat("yyyyMMdd").format(new Date());

                try {
                    String s = ResourceUtils.getURL("classpath:").getPath() + "static" + path;
                    System.out.println("文件保存路径" + s);
                    File f = new File(s);
                    f.mkdir();

                    String imageName = new Date().getTime() + file.getOriginalFilename();
                    book.setImgurl(path + File.separator + imageName);
                    System.out.println("图片名称"+imageName);

//                    上传图片
                    file.transferTo(new File(s,imageName));

                    bookMapper.insertBook(book);

//                    书籍添加成功并添加到审评
                    Examine examine = new Examine();
                    examine.setBookid(book.getId());
                    examine.setNumber(book.getNumber());
                    examine.setSupplierid(supplierId);
                    examine.setFlag(StatusConstant.EXAMINE_DEFAULT_VALUE);
  //应该不是书名
                    examine.setTitle(book.getBookname());
                    examineMapper.insertExamine(examine);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    throw new FileUploadErrorException("文件上传地址有误");
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new FileUploadErrorException("文件上传失败");
                }
            }
        }else {
                book1.setNumber(book.getNumber() + book1.getNumber());
                bookMapper.updateBook(book1);

                Examine examine = new Examine();
                examine.setBookid(book.getId());
                examine.setNumber(book.getNumber());
                examine.setSupplierid(supplierId);
                examine.setFlag(StatusConstant.EXAMINE_DEFAULT_VALUE);
  //应该不是书名
                examine.setTitle(book.getBookname());
                examineMapper.insertExamine(examine);
        }
    }
}
